const { getSqlLiteData } = require('../../SqlLiteDB');

module.exports = function setUserRouter (router) {

    //查询用户
    router.get('/getUsers', async function (req, res, next) {
        try {
            let dataContent = JSON.parse(req.query['dataContent']);
            let workid = dataContent.workid;
            let SqlString = "SELECT * FROM USERS U" + (workid ? ` WHERE U.workid='${workid}'` : '');
            let users = await getSqlLiteData(SqlString);


            res.status(200).json({
                users,
            });
        }
        catch (ex) {
            res.status(500).json(ex);
            console.log('ex :>> ', ex);
        }
    });

    //新增或修改用户
    router.post('/updateUser', async function (req, res, next) {
        try {
            let dataContent = JSON.parse(req.body['dataContent']);
            let user = dataContent.user;
            let SqlString = `REPLACE INTO users(workid,username,type,password,is_active) 
                         VALUES ('${user.workid}', '${user.username}', '${user.type}', '${user.password}',${user.is_active})`;
            let result = await getSqlLiteData(SqlString);

            res.status(200).json({
                result,
            });
        }
        catch (ex) {
            res.status(500).json(ex);
            console.log('ex :>> ', ex);
        }
    });

    //删除用户
    router.post('/deleteUser', async function (req, res, next) {
        try {
            let dataContent = JSON.parse(req.body['dataContent']);
            let workid = dataContent.workid;
            let SqlString = `DELETE FROM USERS WHERE workid ='${workid}'`;
            let result = await getSqlLiteData(SqlString);

            res.status(200).json({
                result,
            });
        }
        catch (ex) {
            res.status(500).json(ex);
            console.log('ex :>> ', ex);
        }
    });
};
